package com.simou.controller;

import com.simou.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

//文件的上传下载

@Slf4j
@RestController
@RequestMapping("/common")
public class FileController {
    // springboot配置文件的值
    @Value("${reggie.path}")
    String basePath;

    @PostMapping("/upload")
    public R<String> fileUpload(MultipartFile file){
        log.info(file.toString());

        String originalFilename = file.getOriginalFilename();

        // 为了防止文件名相同导致文件被覆盖，使用UUID随机生成图片名
        String random = UUID.randomUUID().toString();
        assert originalFilename!=null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName =random+suffix;
        // 若指定目录不存在，生成目录
        File file1 = new File(basePath);
        if(!file1.exists()){
            file1.mkdir();
        }

        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }

//    将文件内容显示在浏览器上
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        log.info("name为{}",name);

        FileInputStream inputStream = new FileInputStream(basePath+name);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("image/jpeg");

        int len = 0;
        byte[] bytes = new byte[1024];
        while((len = inputStream.read(bytes)) !=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }

        outputStream.close();
        inputStream.close();

    }
}
